package com.spvs.system.utils;

public class SnowflakeIdWorkerUtils {
    private static volatile SnowflakeIdWorkerUtils instance; // 单例实例

    private long datacenterId; // 数据中心ID
    private long workerId; // 工作机器ID
    private long sequence = 0L; // 序列号

    private long twepoch = 1288834974657L; // 初始时间戳

    private long datacenterIdBits = 5L; // 数据中心ID所占的位数
    private long workerIdBits = 5L; // 工作机器ID所占的位数
    private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); // 数据中心ID最大值
    private long maxWorkerId = -1L ^ (-1L << workerIdBits); // 工作机器ID最大值

    private long sequenceBits = 12L; // 序列号在ID中占的位数

    private long workerIdShift = sequenceBits; // 工作ID偏移量
    private long datacenterIdShift = sequenceBits + workerIdBits; // 数据中心ID偏移量
    private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; // 时间戳的偏移量

    private long sequenceMask = -1L ^ (-1L << sequenceBits); // 生成序列的掩码

    private long lastTimestamp = -1L; // 上一次生成ID的时间截

    // 双重检查锁实现单例
    public static SnowflakeIdWorkerUtils getInstance(long workerId, long datacenterId) {
        if (instance == null) {
            synchronized (SnowflakeIdWorkerUtils.class) {
                if (instance == null) {
                    instance = new SnowflakeIdWorkerUtils(workerId, datacenterId);
                }
            }
        }
        return instance;
    }

    public SnowflakeIdWorkerUtils(long workerId, long datacenterId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public synchronized long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp)
            // 简单的时间回拨处理逻辑：如果时间回拨不超过5毫秒，等待后重试
            if (lastTimestamp - timestamp < 5) {
                try {
                    Thread.sleep(lastTimestamp - timestamp);
                    timestamp = timeGen();
                    if (timestamp < lastTimestamp) {
                        throw new RuntimeException("Clock moved backwards. Refusing to generate id");
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException("Sleep interrupted", e);
                }
            } else {
                throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
            }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }
}
